import 'dart:convert';
import 'dart:async';

import 'package:alipay_kit/alipay_kit.dart';
import 'package:dio/dio.dart';

/**
 * 充值页面
 * author wim
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/event/LoginEvent.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:wechat_kit/wechat_kit.dart';

class RechargePage extends StatefulWidget {
  String order_id = "", order_num = "";
  RechargePage({Key key, @required this.order_id, @required this.order_num})
      : super(key: key);

  @override
  _RechargePageState createState() => _RechargePageState();
}

class _RechargePageState extends State<RechargePage> {
  Wechat _wechat = Wechat()
    ..registerApp(
      appId: WX_APPID,
      universalLink: WECHAT_UNIVERSAL_LINK,
    );
  List<String> services = new List();
  List<bool> bools = new List();
  String pay_way = "alipay";
  String token = "", price = "0.00";
  StreamSubscription<WechatPayResp> _pay;
  Alipay _alipay = Alipay();

  StreamSubscription<AlipayResp> _alipay_res;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      getPrice();
    });
    _pay = _wechat.payResp().listen(_listenPay);
    _alipay_res = _alipay.payResp().listen(_listenAliPay);
  }

  void _listenAliPay(AlipayResp resp) {
    // String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    if (resp != null && resp.resultStatus == 9000) {
      Fluttertoast.showToast(msg: "支付成功");
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop();
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: "支付失败");
    }
  }

  void _listenPay(WechatPayResp resp) {
    print(resp);
    if (resp.errorCode == WechatSdkResp.ERRORCODE_SUCCESS) {
      Fluttertoast.showToast(msg: "支付成功");
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop();
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: "支付失败");
    }
    // _showTips('支付', content);
  }

  @override
  void dispose() {
    if (_alipay_res != null) {
      _alipay_res.cancel();
    }
    if (_pay != null) {
      _pay.cancel();
    }
    super.dispose();
  }

  getPrice() async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = SignType.USER_GROUP_GET_PRICE;
    Response<String> response =
        await HttpUtil().post(Api.USER_GROUP_PRICE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      // Navigator.of(context).pop();
      price = userMap['data']['price'].toString();
      setState(() {});
    } else {
      Fluttertoast.showToast(msg: msg);
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(
          '成为店长',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        backgroundColor: white,
        brightness: Brightness.light,
        elevation: 0.2,
        iconTheme: IconThemeData(color: black_99),
      ),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  color: white, borderRadius: BorderRadius.circular(5)),
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text('需支付',
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE - 5))),
                  Container(
                    height: DP_8,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text("$price",
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(BIG_FONT_SIZE * 2 - 15))),
                    ],
                  ),
                ],
              ),
            ),
            Padding(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_30)),
              child: Text('选择充值方式',
                  style: TextStyle(
                      color: black,
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE))),
            ),
            Container(
              width: double.infinity,
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  0,
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20)),
              decoration: BoxDecoration(
                  color: white, borderRadius: BorderRadius.circular(15)),
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Image.asset(
                        "images/icon_ipay.png",
                        scale: 1.5,
                      ),
                      Container(
                        width: 10,
                      ),
                      Expanded(
                        child: Text('支付宝支付',
                            style: TextStyle(
                                color: black,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                      ),
                      Checkbox(
                          value: pay_way == "alipay",
                          activeColor: mainColor,
                          checkColor: black_99,
                          materialTapTargetSize: MaterialTapTargetSize.padded,
                          onChanged: (bool x) {
                            if (pay_way == "wxpay") {
                              pay_way = "alipay";
                            }
                            setState(() {});
                          }),
                    ],
                  ),
                  Container(
                    height: 5,
                  ),
                  Divider(
                    height: 1.0,
                    indent: 0.0,
                    color: grey,
                  ),
                  Container(
                    height: 5,
                  ),
                  Row(
                    children: <Widget>[
                      Image.asset(
                        "images/icon_wechat.png",
                        scale: 1.5,
                      ),
                      Container(
                        width: 10,
                      ),
                      Expanded(
                        child: Text('微信支付',
                            style: TextStyle(
                                color: black,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                      ),
                      Checkbox(
                          value: pay_way == "wxpay",
                          activeColor: mainColor,
                          checkColor: black_99,
                          materialTapTargetSize: MaterialTapTargetSize.padded,
                          onChanged: (bool x) {
                            if (pay_way == "alipay") {
                              pay_way = "wxpay";
                            }
                            setState(() {});
                          }),
                    ],
                  ),
                ],
              ),
            ),
            new Container(
              width: double.infinity,
              margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_40)),
              height: ScreenUtil.getInstance().setWidth(DP_90),
              decoration: new BoxDecoration(
                  color: mainColor, borderRadius: BorderRadius.circular(DP_80)),
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
              child: new FlatButton(
                child: new Padding(
                  padding: EdgeInsets.all(0.0),
                  child: new Text(
                    "确定支付",
                    style: new TextStyle(
                        color: Colors.white,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ),
                onPressed: () {
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "获取表单中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  getPayForm(widget.order_id, widget.order_num);
                  // register();
                  // _checkSub(context);
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  getPayForm(String order_id, String order_num) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = order_id;
    map['pay_method'] = pay_way;
    map['sign_type'] = SignType.GET_USER_PAY_FORM;
    Response<String> response =
        await HttpUtil().post(Api.GET_USER_GROUP_PAY_FORM, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    if (code == 1 && mounted) {
      if (pay_way == "alipay") {
        _alipay.payOrderSign(orderInfo: userMap['data']['pay_parameters']);
      } else {
        //  Fluttertoast.showToast(msg: "微信支付暂未开通");
        var jsonTxt1 = userMap['data']['pay_parameters'];
        Map<String, dynamic> user = json.decode(jsonTxt1);
        print(user);
        _wechat.pay(
          appId: user['appid'].toString(),
          partnerId: user['partnerid'].toString(),
          prepayId: user['prepayid'].toString(),
          package: user['package'].toString(),
          nonceStr: user['noncestr'].toString(),
          timeStamp: user['timestamp'].toString(),
          sign: user['sign'],
        );
      }
      // // Navigator.of(context).pop();
      // getPayForm(userMap['data']['order_id'], userMap['data']['order_num']);
    } else {
      Fluttertoast.showToast(msg: msg);
    }
  }

  creatScope(List<String> scops) {
    var result = new List<Widget>();
    for (int i = 0; i < scops.length; i++) {
      result.add(new GestureDetector(
        onTap: () {
          for (int n = 0; n < bools.length; n++) {
            if (i != n) {
              bools[n] = false;
            } else {
              bools[i] = !bools[i];
            }
          }
          if (bools[i]) {
            // car_type+=scops[i].id+",";
          } else {
            // car_type.replaceAll(scops[i].id+",", "");
          }
          setState(() {});
        },
        child: new Container(
          width: (MediaQuery.of(context).size.width -
                  2 * ScreenUtil.getInstance().setHeight(DP_30)) /
              3,
          padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_10)),
          child: new Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_10)),
            decoration: BoxDecoration(
                color: Color.fromARGB(255, 253, 246, 245),
                borderRadius: BorderRadius.circular(5),
                border: Border.all(
                    color: bools[i]
                        ? Colors.red[600]
                        : Color.fromARGB(255, 253, 246, 245),
                    width: 2)),
            child: Column(
              children: <Widget>[
                Text(
                  MONEY + scops[i],
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                      color: Color.fromARGB(255, 233, 63, 51)),
                ),
                Text(
                  "送" + scops[i] + "积分",
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
                      color: Colors.red[400]),
                )
              ],
            ),
          ),
        ),
      ));
    }
    return result;
  }
}
